/*
 * Copyright 2013 Mounir IDRASSI  (mounir.idrassi@idrix.fr, for IDRIX)
 *
 * This file is part of SimCardManager.
 *
 * SimCardManager is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * SimCardManager is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SimCardManager.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

// PhoneBookDlg.cpp : implementation of the CPhoneBookDlg class
//
/////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "resource.h"

#include "MainDlg.h"
#include "PhoneBookDlg.h"


LRESULT CPhoneBookDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
   // center the dialog on the screen
   CenterWindow(GetParent());

   // set icons
   HICON hIcon = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), 
      IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR);
   SetIcon(hIcon, TRUE);
   HICON hIconSmall = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), 
      IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
   SetIcon(hIconSmall, FALSE);

   m_list.Attach(GetDlgItem(IDC_LIST));

   if (m_type == ADN_DLG)
      SetWindowText(_T("Phonebook (Abbreviated Dial Numbers)"));
   else if (m_type == FDN_DLG)
      SetWindowText(_T("Fixed Dialing Numbers (FDN)"));
   else
      SetWindowText(_T("SMS Messages"));

   TCHAR szValue[1024];
   m_count = 0;
   if (m_type == SMS_DLG)
   {  
      m_list.InsertColumn(0, _T("From"), LVCFMT_LEFT);
      m_list.InsertColumn(1, _T("Date"), LVCFMT_LEFT);
      m_list.InsertColumn(2, _T("Message"), LVCFMT_LEFT);

      for (SmsEntryList::iterator It = m_smsList->m_list.begin(); It != m_smsList->m_list.end();It++)
      {
         // MultiByteToWideChar(CP_ACP, 0, It->m_number.c_str(), -1, szValue, 1024);
         int index = m_list.InsertItem(LVIF_PARAM | LVIF_TEXT, 0, It->m_number.c_str(), 0, 0, 0, m_count++);

         // MultiByteToWideChar(CP_ACP, 0, It->m_timestamp.c_str(), -1, szValue, 1024);
         m_list.SetItemText(index, 1, It->m_timestamp.c_str());
         time_t t = mktime(&It->m_timetuple);
         m_list.SetItemData(index, (DWORD_PTR) t);

         // MultiByteToWideChar(CP_ACP, 0, It->m_message.c_str(), -1, szValue, 1024);
         m_list.SetItemText(index, 2, It->m_message.c_str());
      }
   }
   else
   {
      m_list.InsertColumn(0, _T("Name"), LVCFMT_LEFT);
      m_list.InsertColumn(1, _T("Number"), LVCFMT_LEFT);

      for (StringMap::iterator It = m_phoneBook->m_list.begin(); It != m_phoneBook->m_list.end();It++)
      {
         MultiByteToWideChar(CP_ACP, 0, It->first.c_str(), -1, szValue, 1024);
         int index = m_list.InsertItem(LVIF_PARAM | LVIF_TEXT, 0, szValue, 0, 0, 0, m_count++);

         MultiByteToWideChar(CP_ACP, 0, It->second.c_str(), -1, szValue, 1024);
         m_list.SetItemText(index, 1, szValue);
      }
   }

   // automatic resizing of columns
   m_list.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER);
   m_list.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER);
   if (m_type == SMS_DLG)
      m_list.SetColumnWidth(2, LVSCW_AUTOSIZE_USEHEADER);

   return TRUE;
}

LRESULT CPhoneBookDlg::OnBnClickedExport(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
   LPCTSTR szDesc;
   if (m_type == ADN_DLG)
   {
      szDesc = _T("PhoneBook.txt");
   }
   else if (m_type == FDN_DLG)
   {
      szDesc = _T("FDN.txt");
   }
   else
      szDesc = _T("SMS.txt");

   CFileDialog dlg(FALSE, _T("txt"), szDesc, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, NULL, m_hWnd);
   if ((dlg.DoModal() == IDOK) && _tcslen(dlg.m_szFileName))
   {
      FILE* f = _tfopen(dlg.m_szFileName, _T("wt"));
      if (f)
      {
         CWaitCursor cursor;
         TCHAR szLabel[1024];

         if (m_type == SMS_DLG)
         {
            for (int i = 0; i < m_count; i++)
            {
               m_list.GetItemText(i, 0, szLabel, 1024);
               if (_tcslen(szLabel) < 30)
               {
                  wmemset(&szLabel[_tcslen(szLabel)], L' ', 30 - _tcslen(szLabel));
                  szLabel[30] = 0;
               }
               _ftprintf(f, _T("%s,\t"), szLabel);
               m_list.GetItemText(i, 1, szLabel, 1024);
               _ftprintf(f, _T("%s,\t"), szLabel);
               m_list.GetItemText(i, 2, szLabel, 1024);
               _ftprintf(f, _T("\"%s\"\n"), szLabel);
            }
         }
         else
         {
            if (m_bAscending)
            {
               for (int i = 0; i < m_count; i++)
               {
                  m_list.GetItemText(i, 0, szLabel, 1024);
                  wmemset(&szLabel[_tcslen(szLabel)], L' ', m_phoneBook->m_nameLength - _tcslen(szLabel));
                  szLabel[m_phoneBook->m_nameLength] = 0;
                  _ftprintf(f, _T("%s,\t"), szLabel);
                  m_list.GetItemText(i, 1, szLabel, 1024);
                  _ftprintf(f, _T("%s\n"), szLabel);
               }
            }
            else
            {
               for (int i = m_count - 1; i >= 0; i--)
               {
                  m_list.GetItemText(i, 0, szLabel, 1024);
                  wmemset(&szLabel[_tcslen(szLabel)], L' ', m_phoneBook->m_nameLength - _tcslen(szLabel));
                  szLabel[m_phoneBook->m_nameLength] = 0;
                  _ftprintf(f, _T("%s,\t"), szLabel);
                  m_list.GetItemText(i, 1, szLabel, 1024);
                  _ftprintf(f, _T("%s\n"), szLabel);
               }
            }
         }
         fclose(f);
      }
      else
         MessageBox(_T("Failed to open the selected file for writing"), _T("I/O Error"), MB_ICONERROR);
   }

   return 0;
}

int CPhoneBookDlg::LVCompare(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) {
   CPhoneBookDlg* dlg = (CPhoneBookDlg*) lParamSort;
   CListViewCtrl* pListCtrl = &dlg->m_list;
   bool bAscending = dlg->m_bAscending;

   LVFINDINFO info = {0};
   int nIndex1, nIndex2;
   info.flags = LVFI_PARAM;
   info.lParam = lParam1;
   nIndex1=pListCtrl->FindItem(&info, -1);
   info.lParam = lParam2;
   nIndex2=pListCtrl->FindItem(&info, -1);

   if ((dlg->m_type != SMS_DLG) || (dlg->m_iColumn != 1))
   {
      TCHAR szLabel1[512], szLabel2[512];
      pListCtrl->GetItemText(nIndex1, dlg->m_iColumn, szLabel1, 512);
      pListCtrl->GetItemText(nIndex2, dlg->m_iColumn, szLabel2, 512);

      if (bAscending)
         return _tcscmp(szLabel1, szLabel2);
      else
         return _tcscmp(szLabel2, szLabel1);
   }
   else
   {
      time_t t1, t2;
      t1 = (time_t) pListCtrl->GetItemData(nIndex1);
      t2 = (time_t) pListCtrl->GetItemData(nIndex2);

      if (!bAscending) { time_t dummy = t1; t1 = t2; t2 = dummy;}

      if (t1 == t2)
         return 0;
      else if (t1 < t2)
         return -1;
      else
         return 1;
   }
}

LRESULT CPhoneBookDlg::OnNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) {
   LPNMHDR nmhdr = (LPNMHDR) lParam;
   //if (nmhdr->code == NM_RCLICK) {
   //   if (_ListCtrl.GetNextItem(-1, LVNI_SELECTED) != -1) {
   //      POINT p; GetCursorPos(&p);
   //      CMenuHandle m = menupop.GetSubMenu(0);
   //      m.TrackPopupMenu(TPM_LEFTALIGN, p.x, p.y, GetTopLevelParent(),
   //         NULL);
   //   }
   //   return 0;
   //}
   if (nmhdr->code == HDN_ITEMCLICK) {
      LPNMHEADER phdr = (LPNMHEADER) lParam;
      m_iColumn = phdr->iItem;
      m_bAscending = !m_bAscending;
      m_list.SortItems(&LVCompare, (LPARAM)this);

      return 0;
   }
   bHandled = FALSE;
   return 0;
}